package com.example.entity;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSONWriter;

/**
 * @author AiXu
 * @version v1.0
 * @since 2023/9/11 14:19
 */

public record RestBean<T>(int code, T data, String message) {

    //写几个工具方法，用于快速创建RestBean对象
    public static <T> RestBean<T> success(T data, String message){
        if (message == null) {
            message = "请求成功";
        }
        return new RestBean<>(200, data, message);
    }

    public static <T> RestBean<T> failure(int code, String message){
        return new RestBean<>(code, null, message);
    }

    public static <T> RestBean<T> failure(int code){
        return failure(code, "服务器内部错误，请联系管理员");
    }
    //将当前对象转换为JSON格式的字符串用于返回
    public String asJsonString() {
        return JSONObject.toJSONString(this, JSONWriter.Feature.WriteNulls.ordinal());
    }
}
